package com.itheima.controller;

import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    //登录
    @PostMapping("/login.do")
    public String login( String username,String password) throws IOException {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        Result result = loginService.login(user);
        if (result.isFlag()){
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            //response.sendRedirect("/pages/main.html");
            return "redirect:/pages/main.html";
        }else {
           // response.sendRedirect("/login.html");
            return "redirect:/login.html";
        }
    }

    @GetMapping("/user/getUsername.do")
    @ResponseBody
    public Result findByUsername(){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user.getUsername() == null){
            return new Result(false,"请先登录");
        }
        return new Result(true,"获取当前登录用户名称成功",user.getUsername());
    }
}
